<template>
  <div>
    <!-- 标题 -->
    <van-nav-bar
      title="常用联系人"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 收货人 -->
    <div>
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="setaddress"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "address",
  data() {
    return {
      chosenAddressId: "",
      list: [],
    };
  },
  methods: {
    onClickLeft() {
      window.history.go(-1);
    },
    // 获取收货人
    getaddress() {
      this.axios
        .post("apis/kuan_api/address.php", {
          code: 0,
          userid: this.$store.state.user.user_id,
        })
        .then((res) => {
          this.list = res.data.data;
          this.list.forEach((element) => {
            if (element.contactFlag == 1) {
              this.chosenAddressId = element.id;
            }
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 修改默认联系人
    setaddress(index) {
      console.log(index.id);
      this.axios
        .post("apis/kuan_api/address.php", {
          code: 1,
          id: index.id,
          userid: this.$store.state.user.user_id,
        })
        .then((res) => {
          this.$toast.success("修改成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 新增收货人
    onAdd() {
      if (this.$store.state.user.user_id == undefined) {
        this.$dialog
          .confirm({
            title: "提示",
            message: "当前还未登录",
          })
          .then(() => {
            this.$router.push("/login");
          });
      } else {
        this.$router.push("/addressedit");
      }
    },
    // 编辑联系人
    onEdit(index) {
      this.$router.push({
        path: "/addressedit",
        query: { edit: index },
      });
    },
  },
  created() {
    this.getaddress();
  },
};
</script>

<style scoped>
</style>